<?php


namespace app\reception\controller;

use app\common\model\FreqToClassAccess;
use app\common\model\NovelClass;
use app\common\model\NovelClassSon;
use app\common\model\NovelFreq;
use app\common\model\QuickAppInfo;
use app\common\model\QuickLink;
use app\common\model\QuickOpen;
use app\common\model\RechargeActivity;
use app\common\model\RechargeTemplate;
use app\reception\logic\PageLogic;
use think\Db;
use think\db\Expression;

class Page extends Common
{
    protected $middleware = [
        'VerifyAuth' => ['except' => []],
    ];

    private $logic;

    public function __construct(PageLogic $logic = null)
    {
        $this->logic = $logic;
        parent::__construct();
    }

    /**
     * 获取封面
     * @return \think\response\Json
     */
    public function getBanner()
    {
        $seat = input('seat');
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\PageValidate.getBanner');
        if (true !== $result) {
            return errJson($result);
        }
        /**
         * (有归属投放号，并且不是黑名单，并且未被ip屏蔽，并且不是疑似审核员)
         */
        if ($this->isWhite) {
            $type = 1;
        } elseif ($this->user->channel_id && $this->isBlack == 0 && !$this->user->auditor) {
            if (ipUnblocked($this->user)) {
                $type = 1;//广告读者
            } else {
                $type = 2;//地区屏蔽读者
            }
        } else {
            $type = 0;//审核读者
        }
        $where[] = ['quick_id', '=', $this->quickAppId];
        $where[] = ['seat', '=', $seat];
        $where[] = ['type', '=', $type];
        return $this->logic->getBanner($this->user, $where);
    }

    /**
     * 获取推荐位
     * @return \think\response\Json
     * @Author: whh
     */
    public function getRecommendNovels()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\PageValidate.getRecommendNovels');
        if (true !== $result) {
            return errJson($result);
        }
        /**
         * 白名单 = 广告线上
         * 市场用户 || 审核人员 || 黑名单 ：查看审核数据
         * 地区屏蔽 = 地区屏蔽
         * 其他 = 广告线上
         */
        if ($this->isWhite) {
            $type = 1;
        } elseif (!$this->user->channel_id || $this->isBlack || $this->user->auditor) {
            $type = 0;
        } elseif (!ipUnblocked($this->user)) {
            $type = 2;
        } else {
            $type = 1;
        }
        return $this->logic->getRecommendNovels($this->user, $type);
    }


    public function getBatchRecommendNovels(){
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\PageValidate.getBatchRecommendNovels');
        if (true !== $result) {
            return errJson($result);
        }
        /**
         * 白名单 = 广告线上
         * 市场用户 || 审核人员 || 黑名单 ：查看审核数据
         * 地区屏蔽 = 地区屏蔽
         * 其他 = 广告线上
         */
        if ($this->isWhite) {
            $type = 1;
        } elseif (!$this->user->channel_id || $this->isBlack || $this->user->auditor) {
            $type = 0;
        } elseif (!ipUnblocked($this->user)) {
            $type = 2;
        } else {
            $type = 1;
        }
        return $this->logic->getBatchRecommendNovels($this->user, $type);
    }

    /**
     * 充值项
     * @return \think\response\Json
     */
    public function rechargeItems()
    {
        $isVip = input('is_vip');
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\PageValidate.rechargeItems');
        if (true !== $result) {
            return errJson($result);
        }
        if ($isVip == 0 && $isVip != '') {
            $where[] = ['vipdays', '=', 0];
        }
        if ($isVip == 1) {
            $where[] = ['vipdays', '<>', 0];
        }
        $link_id = $this->user->link_id;
        $link = QuickLink::where("id", $link_id)->field("id,template_id")->find();
        $template_id = 0;
        if ($link && $link->template_id){
            $temp = RechargeTemplate::get($link->template_id);
            if ($temp){
                $template_id = $link->template_id;
            }
        }
        $where[] = ['is_activity', '=', 0];
        $where[] = ['state', '=', 1];
        $data['to_login'] = 0;
        if (!$this->user->channel_id || $this->user->auditor) {
            $data['to_login'] = 1;//要去登陆
        }
        $data['items'] = $this->logic->getRechargeItems($this->user, $where, $template_id, $this->quickAppId);
        $data['tips'] = $this->getPayTip();
        return sucJson($data);
    }

    /**
     * 充值描述
     * @return string[]
     */
    private function getPayTip(){
        $contact = QuickAppInfo::where('quick_id', $this->quickAppId)->cache(86400)->value('contact');
        return [
            '客服' . $contact,
            '书币和会员属于虚拟商品，一经购买不得退换',
            '用户使用书币购买收费章节，后期重复阅读无需重新购买',
            '充值后书币到账可能有延迟，2小时内未到账请与客服联系',
            '书点具有时间限制(15天)，过期自动失效，消费时优先扣除距离过期时间最近的书点',
            '未满18周岁的未成年人，应在父母或其他监护人的监护、指导、同意下进行如付费充值、付费阅读等相关操作',
            '在本平台所做的任何操作将视为已获得您的父母或其他监护人的同意并由您和您的父母或其他监护人承担相关法律责任',
        ];
    }

    /**
     * 阅读页下方书籍
     * @return \think\response\Json
     */
    public function readBelowNovels()
    {
        /**
         * 白名单 || (有归属投放号，并且不是黑名单，并且不是疑似审核员)
         */
        if ($this->isWhite || ($this->user->channel_id && $this->isBlack == 0 && !$this->user->auditor)) {
            $where[] = ['type', '=', 'below'];
            /**使用平台设置内容，还是自定义内容*/
            $where[] = ['quick_id', '=', $this->quickAppId];
            if ($this->isWhite) {
                $where[] = ['status', '=', 1];
            } else {
                if (ipUnblocked($this->user)) {
                    $where[] = ['status', '=', 1];
                } else {
                    $where[] = ['status', '=', 2];
                }
            }
            return $this->logic->getReadBelowNovels($this->user, $where);
        } else {
            return sucJson([], 0);
        }
    }


    /**
     * 书库检索项
     * @return \think\response\Json
     */
    public function retrieveItems()
    {
        $cache = 86400;
        $allFreq = NovelFreq::field("id,name")->cache($cache)->select()->toArray();
        $allFreq = array_column($allFreq, null, 'id');
        $allClass = NovelClass::order("wgt desc,id desc")->field("id,name")->cache($cache)->select()->toArray();
        $allClass = array_column($allClass, null, 'id');
        $allSonClass = NovelClassSon::field("id,name,freq_id,class_id")->cache($cache)->select()->toArray();
        $allSonClass = array_column($allSonClass, null, 'id');

        $classIds = array_keys($allClass);
        $orderBy = '';
        if ($classIds) {
            $orderBy = new Expression('field(class_id,' . implode(',', $classIds) . ')');
        }
        $freqToClass = FreqToClassAccess::order($orderBy)->cache($cache)->select()->toArray();
        foreach ($freqToClass as $k => $v) {
            if (isset($allFreq[$v['freq_id']])) {
                $allFreq[$v['freq_id']]['classIds'][] = $v['class_id'];
            }
        }
        foreach ($allSonClass as $k => $v) {
            if (isset($allFreq[$v['freq_id']])) {
                $allFreq[$v['freq_id']]['sonClassIds'][] = $v['id'];
            }
            if (isset($allClass[$v['class_id']])) {
                $allClass[$v['class_id']]['sonClassIds'][] = $v['id'];
            }
            unset($allSonClass[$k]['freq_id']);
            unset($allSonClass[$k]['class_id']);
        }
        $data = [
            'allFreq' => $allFreq,
            'allClass' => $allClass,
            'allSonClass' => $allSonClass,
            'novel_status' => [['status' => 0, 'title' => '连载'], ['status' => 1, 'title' => '完结']],
            'words_types' => [
                ['type' => 1, 'title' => '30万字以内'],
                ['type' => 2, 'title' => '30-50万字'],
                ['type' => 3, 'title' => '50-100万字'],
                ['type' => 4, 'title' => '100-200万字'],
                ['type' => 5, 'title' => '200万字已上'],
            ],
            'order_types' => [
                ['type' => 1, 'title' => '最高人气'],
                ['type' => 2, 'title' => '最近更新'],
            ],
        ];
        return sucJson($data);
    }

    /**
     *
     * @return \think\response\Json
     */
    public function openFace()
    {
        if (!$this->isWhite && (!$this->user->channel_id || $this->isBlack || $this->user->auditor)) {
            return errJson('no');
        }
        $user = $this->user;
        /**快应用*/
        $where[] = ['status', '=', 1];
        $where[] = ['', 'exp', Db::raw("FIND_IN_SET($this->quickAppId,quick_apps)")];

        /**用户群体*/
        $map1[] = ['test_user_id', '=', $user->id];
        if (!$this->isWhite) {
            if (ipUnblocked($this->user)) {
                $map2[] = ['user_grep', 'in', [1, 0]];
            } else {
                $map2[] = ['user_grep', 'in', [2, 0]];
            }
        } else {
            $map2[] = ['user_grep', 'in', [1, 0]];
        }
        /**充值条件*/
        $pur = Db::table("quick_pay_user_record")->where("uid",$user->id)->field("id,pay_money,pay_num")->find();
        if ($pur) {
            $map2[] = ['is_pay', 'in', [0, 1]];
        } else {
            $map2[] = ['is_pay', 'in', [0, 2]];
        }
        /**
         * 书币余额
         */
        if ($user->book_coin >= 5000) {
            $map2[] = ['coin_balance', '=', 1];
        } elseif ($user->book_coin >= 2000) {
            $map2[] = ['coin_balance', 'in', [1, 5]];
        } elseif ($user->book_coin >= 500) {
            $map2[] = ['coin_balance', 'in', [1, 4]];
        } elseif ($user->book_coin >= 200) {
            $map2[] = ['coin_balance', 'in', [1, 3]];
        } elseif ($user->book_coin >= 0) {
            $map2[] = ['coin_balance', 'in', [1, 2]];
        }
        $query = $list = QuickOpen::where($where)->where(function ($query) use ($map1, $map2) {
            $query->whereOr([$map1, $map2]);
        });

        $list = $query->order("wgt desc,id desc")->fetchSql(false)->select();
//        echo QuickOpen::getLastSql();die;
        $open = null;
        $now = time();
        foreach ($list as $k => $v) {
            if ($v['is_pay'] == 1) {
                if (!$pur){
                    continue;
                }elseif ($pur['pay_money'] < $v['mini_pay_money']){
                    continue;
                }
            }
            if ($v['register_type'] == 1) {
                $regtime = strtotime($user->regtime);
                $startTime = 0;
                $endTime = INF;
                if ($v['register_start']) {
                    $startTime = $regtime + ($v['register_start'] * 86400);
                }
                if ($v['register_end']) {
                    $endTime = $regtime + ($v['register_end'] * 86400);
                }
                if ($now < $startTime || $now > $endTime) {
                    continue;
                }
            }
            $open = $v;
            break;
        }
        if ($open) {
            $data['type'] = $open['type'];
            $data['pic'] = config('img_domain') . $open['pic'];
            if ($open['type'] == 1) {
                //推书
                $data['novel_id'] = $open['novel_id'];
            } elseif ($open['type'] == 2) {
                //活动充值
                $data['activity_id'] = $open['activity_id'];
            } else {
                $data['jump_url'] = $open['jump_url'];
                //外部链接
            }
            return sucJson($data);
        } else {
            return errJson('无开屏');
        }
    }

    /**
     * 活动充值项
     * @return \think\response\Json
     */
    public function getActivityRecharge(){
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\PageValidate.getActivityRecharge');
        if (true !== $result) {
            return errJson($result);
        }
        $activityId = input('activity_id');
        $activity = RechargeActivity::get($activityId);
        if (!$activity){
            return errJson('活动不存在');
        }
        $item = $activity->item;
        if (!$item){
            return errJson('充值项不存在');
        }
        $data = [
            'img' => $activity->img,
            'pay_item' => [
                'id' => $item->id,
                'total_fee' => $item->total_fee,
                'virtual_currency' => $item->virtual_currency,
                'point_gift' => $item->point_gift,
                'vipdays' => $item->vipdays,
            ],
            'tips' => $this->getPayTip()
        ];
        return sucJson($data);
    }
}